<template>
  <div class="block">
    <el-alert
      title="选择商品，为指定的商品设置相关参数"
      type="warning"
      :closable="false"
    >
    </el-alert>

    <div class="demo">
      <span class="demonstration"> 选择商品: </span>
      <el-cascader
        v-model="value"
        :options="options"
        :props="{ checkStrictly: true }"
        clearable
        @change="handleChange"
      ></el-cascader>
    </div>

    <div>
      <el-tabs v-model="activeName" @tab-click="handleClick">
        <!-- <el-tab-pane label="添加属性" name="first">
          <el-button type="primary" round  @click="addAttribute">添加属性</el-button>
        </el-tab-pane> -->
        <el-tab-pane label="添加规格" name="second">
          <el-button
            type="primary"
            :disabled="isDisabled()"
            @click="addSpecification"
            >添加规格</el-button
          >
        </el-tab-pane>
      </el-tabs>
    </div>

    <el-table
      v-if="isSpecificationInfo"
      :data="tableData"
      style="width: 100%"
      border
    >
      <el-table-column label="id" width="150">
        <template slot-scope="scope">
          <i class="el-icon-time"></i>
          <span style="margin-left: 10px">{{ scope.row.id }}</span>
        </template>
      </el-table-column>

      <el-table-column label="属性" width="150">
        <template slot-scope="scope">
          <i class="el-icon-time"></i>
          <span style="margin-left: 10px">{{ scope.row.attribute.name }}</span>
        </template>
      </el-table-column>

      <el-table-column label="属性值" width="150">
        <template slot-scope="scope">
          <i class="el-icon-time"></i>
          <span style="margin-left: 10px">{{
            scope.row.attribute_value.name
          }}</span>
        </template>
      </el-table-column>

      <el-table-column label="库存" width="150">
        <template slot-scope="scope">
          <i class="el-icon-time"></i>
          <span style="margin-left: 10px">{{ scope.row.inventory }}</span>
        </template>
      </el-table-column>

      <el-table-column label="价格" width="150">
        <template slot-scope="scope">
          <i class="el-icon-time"></i>
          <span style="margin-left: 10px">{{ scope.row.price }}</span>
        </template>
      </el-table-column>

      <el-table-column label="操作">
        <template slot-scope="scope">
          <el-button
            size="mini"
            @click="handleEditCategory(scope.$index, scope.row)"
            >编辑</el-button
          >
          <el-button
            size="mini"
            type="danger"
            @click="handleDelete(scope.$index, scope.row)"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <!-- Dialog模态框 -->
    <el-dialog title="操作" :visible.sync="dialogFormVisible">
      <el-form
        :model="formdata"
        ref="numberValidateForm"
        label-width="100px"
        class="demo-ruleForm"
      >
        <el-form-item label="属性" prop="name">
          <el-input
            type="text"
            v-model="formdata.Attribute"
            autocomplete="off"
          ></el-input>
        </el-form-item>

        <el-form-item label="属性值" prop="name">
          <el-input
            type="text"
            v-model="formdata.Attribute_value"
            autocomplete="off"
          ></el-input>
        </el-form-item>

        <el-form-item label="库存" prop="name">
          <el-input
            type="text"
            v-model="formdata.Inventory"
            autocomplete="off"
          ></el-input>
        </el-form-item>

        <el-form-item label="价格" prop="name">
          <el-input
            type="text"
            v-model="formdata.Price"
            autocomplete="off"
          ></el-input>
        </el-form-item>

        <div>
          <el-button @click="handleCancel">取 消</el-button>
          <el-button type="primary" @click="handleSave">确 定</el-button>
        </div>
      </el-form>
    </el-dialog>

    <!-- 分页 -->
    <div class="block">
      <el-pagination
        :current-page="pager.currentPage"
        :page-size="pager.pageSize"
        layout="prev, pager, next, jumper,sizes, total"
        :total="pager.totalSize"
        :page-sizes="[5, 10, 15, 20]"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      >
      </el-pagination>
    </div>
  </div>
</template>


<script>
import { getlistMerchandise } from "../api/productlist";
import {
  getSpecificationsBymerchandiseId,
  addSpecifications,
  modSpecifications,
  delSpecifications,
} from "../api/specifications";
export default {
  data() {
    return {
      // 是否显示规格表
      isSpecificationInfo: false,

      // 模态框状态
      dialogFormVisible: false,

      parentData: "",
      currentMerchandiseId: 0,
      sumData: [],

      formdata: {
        id: 0,
        merchandiseId: 0,
        Attribute: "",
        Attribute_value: "",
        Inventory: "",
        Price: "",
      },
      //这个装规格表的返回
      tableData: [],

      pager: {
        //每页显示条目个数
        pageSize: 1000,
        currentPage: 1,
        totalSize: 0,
      },
      // 初始化索引，用于修改
      curIndex: 0,
      activeName: "second",
      value: [],
      options: [],
    };
  },
  methods: {
    showInput() {
      this.inputVisible = true;
      this.$nextTick(() => {
        this.$refs.saveTagInput.$refs.input.focus();
      });
    },

    addAttribute() {},
    // 添加规格
    addSpecification() {
      this.dialogFormVisible = true;

      this.formdata.Attribute = "";
      this.formdata.Attribute_value = "";
      this.formdata.Inventory = "";
      this.formdata.Price = "";
    },
    // 编辑时
    handleEditCategory(index, row) {
      // console.log(index);
      // console.log(row);
      this.dialogFormVisible = true;
      this.formdata.id = row.id;
      this.formdata.merchandiseId = row.merchandiseId;
      this.formdata.Attribute = row.attribute.name;
      this.formdata.Attribute_value = row.attribute_value.name;
      this.formdata.Inventory = row.inventory;
      this.formdata.Price = row.price;
      this.curIndex = index;
    },
    // 删除
    handleDelete(index, row) {
      console.log(index, row);
      console.log(row.id);
      //通过row.id找到当前的id
      this.$confirm("此操作将永久删除该数据, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          delSpecifications(row.id).then(({ data }) => {
            console.log(data);
            this.tableData.splice(index, 1);
            this.pager.totalSize -= 1;
            let nun = parseInt(this.pager.totalSize / this.pager.pageSize) + 1;
            if (
              //判断取余后为零 pager.pageindex-1
              parseInt(this.pager.totalSize % this.pager.pageSize) === 0 &&
              this.pager.currentPage === nun
            ) {
              this.pager.currentPage -= 1;
            }
            //重新拉取
            this.fetchData();
          });
          this.$message({
            type: "success",
            message: "删除成功!",
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    // 取消按钮
    handleCancel() {
      this.dialogFormVisible = false;
    },
    // 确定按钮
    handleSave() {
      this.dialogFormVisible = false;

      if (this.formdata.id === 0) {
        if (
          this.formdata.Price == "" ||
          this.formdata.Attribute == "" ||
          this.formdata.Attribute_value == "" ||
          this.formdata.Inventory == ""
        ) {
          this.$notify({
            title: "警告",
            message: "你有未填写的信息",
            type: "warning",
            position: "top-right",
          });
          this.$notify({
            title: "警告",
            message: "你有未填写的信息",
            type: "warning",
            position: "bottom-right",
          });
          this.$notify({
            title: "警告",
            message: "你有未填写的信息",
            type: "warning",
            position: "bottom-left",
          });
          this.$notify({
            title: "警告",
            message: "你有未填写的信息",
            type: "warning",
            position: "top-left",
          });
        } else {
          //添加规格
          addSpecifications(this.formdata)
            .then((res) => {
              this.tableData.push(res.data);
              this.$message({
                message: "添加分类成功",
                type: "success",
              });
              this.fetchData();
            })
            .catch((err) => {
              console.log(err);
            });
        }
      } else {
        //修改规格接口
        modSpecifications(this.formdata.id, this.formdata)
          .then((res) => {
            this.tableData.splice(this.curIndex, 1, res.data);
            console.log(this.formData);
            this.fetchData();
          })
          .catch((err) => {
            console.log(err);
          });
      }
    },

    //是否禁用
    isDisabled() {
      if (this.parentData == "" || this.parentData == undefined) {
        return true;
      }
      return false;
    },
    //拉取数据
    fetchData() {
      let params = {
        pager: this.pager,
      };

      // 获取所有商品
      getlistMerchandise(params.pager)
        .then((res) => {
          var resful = res.data;
          this.sumData = resful.data;
          // console.log(this.sumData);

          (this.options = []),
            this.sumData.map((x) => {
              let currentGrade = {
                id: 0,
                parentId: 0,
                value: "",
                label: "",
                // children: [],
              };
              currentGrade.id = x.id;
              currentGrade.value = x.name;
              currentGrade.label = x.name;

              // Object.assign方法用于对象的合并，
              // 将router添加到{}  并赋给obj对象中
              let obj = Object.assign({}, currentGrade);

              this.options.push(obj);

              console.log(this.options);
            });
        })
        .catch((err) => {
          console.log(err);
        });
    },
    //选择商品时
    handleChange(value) {
      this.parentData = value[value.length - 1];

      this.options.map((x) => {
        if (x.value == value) {
          //currentMerchandiseId等于当前商品的id
          this.currentMerchandiseId = x.id;

          this.formdata.merchandiseId = this.currentMerchandiseId;
        }
      });

      console.log(this.parentData);

      //如果输入框没选择商品
      if (this.parentData == undefined || this.parentData == "") {
        this.tableData = [];
      } else {
        //获取指定商品的规格
        getSpecificationsBymerchandiseId(this.currentMerchandiseId)
          .then((res) => {
            this.tableData = res.data;

            this.isSpecificationInfo = true;
            // console.log(this.tableData);
          })
          .catch((err) => {
            console.log(err);
          });
      }
    },
    handleClick(tab, event) {
      console.log(tab, event);
      console.log(tab.label);
    },
    // 改变页大小来拉取数据
    handleSizeChange(val) {
      this.pager.pageSize = val;
      this.fetchData();
    },
    // 通过页码来拉取数据
    handleCurrentChange(val) {
      this.pager.currentPage = val;
      this.fetchData();
    },
  },
  mounted() {
    this.fetchData();
  },
};
</script>

<style>
.demo {
  margin-top: 30px;
}
</style>